import JSEncrypt from 'jsencrypt'

export default {
	isFloat(num) {
		const y = String(num).indexOf(".") + 1; //获取小数点的位置
		if (y > 0) {
			return true
		} else {
			return false
		}
	},
	/**
	 * 控制header显示和fixed
	 * @param {Object} _className
	 * @param {Object} _fixed
	 */
	fixHeader(_className, _fixed) {
		let query = uni.createSelectorQuery().select(_className);

		query.boundingClientRect(data => {
			// console.log(data)
			if (data.top > 0) {
				_fixed = false
			} else {
				_fixed = true
			}
		}).exec();
	},
	cleanArray(actual) {
		const newArray = []
		for (let i = 0; i < actual.length; i++) {
			if (actual[i]) {
				newArray.push(actual[i])
			}
		}
		return newArray
	},
	jsonToQuery(json) {
		for (let key in json) {
			if (json[key] == null || json[key] == undefined) {
				delete json[key]
			}
		}
		if (!json) return ""
		return this.cleanArray(Object.keys(json).map(key => {
			if (json[key] === undefined) return ""
			return encodeURIComponent(key) + "=" +
				encodeURIComponent(json[key])
		})).join("&")
	},
	/**
	 * 通过经纬度计算距离（KM）
	 * @param {Object} latlng1
	 * @param {Object} latlng2
	 */
	getDistance(latlng1, latlng2) {
		// console.log("distanceFlt==", latlng1, latlng2)
		let lat1 = latlng1.latitude;
		let lng1 = latlng1.longitude;
		let lat2 = latlng2.latitude;
		let lng2 = latlng2.longitude;
		if (lat1 == null || lng1 == null || lat2 == null || lng2 == null) {
			return 0;
		}
		var radLat1 = (lat1 * Math.PI) / 180.0;
		var radLat2 = (lat2 * Math.PI) / 180.0;
		var a = radLat1 - radLat2;
		var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
			Math.sin(b / 2), 2)));
		s = s * 6378.137; // EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		// return s * 1000;
		return s.toFixed(2);
	},
	uuid() {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for (var i = 0; i < 36; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
		s[8] = s[13] = s[18] = s[23] = "-";
		var uuid = s.join("");
		return uuid;
	},
	formatDate(value = Date.now(), format = "Y-M-D h:m:s") {
		const formatNumber = n => `0${n}`.slice(-2);
		const date = new Date(Number(value));
		const formatList = ["Y", "M", "D", "h", "m", "s"];
		const resultList = [];
		resultList.push(date.getFullYear().toString());
		resultList.push(formatNumber(date.getMonth() + 1));
		resultList.push(formatNumber(date.getDate()));
		resultList.push(formatNumber(date.getHours()));
		resultList.push(formatNumber(date.getMinutes()));
		resultList.push(formatNumber(date.getSeconds()));
		for (let i = 0; i < resultList.length; i++) {
			format = format.replace(formatList[i], resultList[i]);
		}
		return format;
	},
	getDateToNewData(diffValue) {
		//2021-06-20 09:23:12
		//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
		var dateBegin = diffValue; //将-转化为/，使用new Date
		console.log("dateBegin", dateBegin)
		var dateEnd = new Date(); //获取当前时间
		var dateDiff = dateEnd.getTime() - dateBegin; //时间差的毫秒数
		var monthC = Math.floor(dateDiff / (24 * 3600 * 1000 * 30)); //计算出相差月数
		var leaveMon = dateDiff % (24 * 3600 * 1000 * 30); //计算月数后剩余的毫秒数
		var weekC = Math.floor(leaveMon / (24 * 3600 * 1000 * 7)); //计算出相差星期数
		var leaveWeek = leaveMon % (24 * 3600 * 1000 * 7); //计算星期数剩余的毫秒数
		var dayC = Math.floor(leaveWeek / (24 * 3600 * 1000)); //计算出相差天数
		var leave1 = leaveWeek % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
		//计算相差秒数
		var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000);
		var timesString = '';
		if (monthC != 0) {
			if (monthC > 6) {
				var timearr = diffValue.substring(0, 10).split("-");
				var timestrS = "" + timearr[0] + "年" + timearr[1] + "月" + timearr[2] + "日"
				timesString = timestrS
			} else if (monthC == 6) {
				timesString = '半年前'
			} else if (monthC < 6) {
				timesString = monthC + '月前'
			}
		} else if (monthC == 0 && weekC != 0) {
			timesString = weekC + '周前';
		} else if (weekC == 0 && dayC != 0) {
			timesString = dayC + '天前';
		} else if (dayC == 0 && hours != 0) {
			timesString = hours + '小时前';
		} else if (hours == 0 && minutes != 0) {
			timesString = minutes + '分钟前';
		}
		return timesString;
	},
	//JS 计算两个时间戳相差年月日时分秒
	calculateDiffTime(surplusTime) {
		let runTime = parseInt(surplusTime / 1000);
		let year = Math.floor(runTime / 86400 / 365);
		runTime = runTime % (86400 * 365);
		let month = Math.floor(runTime / 86400 / 30);
		runTime = runTime % (86400 * 30);
		let day = Math.floor(runTime / 86400);
		runTime = runTime % 86400;
		let hour = Math.floor(runTime / 3600);
		runTime = runTime % 3600;
		let minute = Math.floor(runTime / 60);
		runTime = runTime % 60;
		let second = runTime;
		let result = {
			year: (year && year >= 10) ? year : `0${year}`,
			month: (month && month >= 10) ? month : `0${month}`,
			day: (day && day >= 10) ? day : `0${day}`,
			hour: (hour && hour >= 10) ? hour : `0${hour}`,
			minute: (minute && minute >= 10) ? minute : `0${minute}`,
			second: (second && second >= 10) ? second : `0${second}`,
		};
		if (year === 0 && month === 0 && day === 0) {
			return `${result.hour}时${result.minute}分${result.second}秒`;
		} else if (year === 0 && month === 0) {
			return `${result.day}天${result.hour}时${result.minute}分${result.second}秒`;
		} else if (year === 0) {
			return `${result.month}月${result.day}天${result.hour}时${result.minute}分${result.second}秒`;
		} else {
			return `${result.year}年${result.month}月${result.day}天${result.hour}时${result.minute}分${result.second}秒`;
		}
	},
	rsaDecrypt(data) {
		const decryptor = new JSEncrypt()
		decryptor.setPrivateKey(`-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDWZBewflJt+NTKY/bVWtn5aoJjF2a2hF7g3q+KevrXe7y3xJ/V
gMUUdp0/LVvl/YGMGS0Tro8PqUgh66CgqeNRBeREJd5H1Ns7VbFZKKVYnNWS4dWI
SaXeDCyD5Xma39tM2DJHYi68UngAzGNnRVXQuk5W4WY1am+WVtYhIFTU7wIDAQAB
AoGBALGUPrsGJyjIDxmFK5MVqa8aNd32KDHN+viv+x7tNpD+ARcGWo3yF0wX46/M
1m3uSTvOLrQ6xmzmfsT58xahIZMa/5zLtY2t7vXtjeVh1vFcUV3KqUvmcaD5QjN+
H6eZ015ecnAXfzAusgOMzbplR3FIjmUYSgHa4wGQnbjr9vnhAkEA6W4daoJNO8yQ
WY93CUhdyxNxwlAIu+XdOkNOhGMlfIhAcHcUBL18omaRb5imH4Y1n5UtN6hLg9rm
HQ1sSfHF9QJBAOseuAE9CSnCFOvakIATfYehOJbqGv4FFcOUEqZItBWI/3TDJjBh
WSBHOU31hbtHV0U0uz2oIoGxgpPEeUH8fNMCQH8imCbgXQxKt/vvZVfK8Dqgln7M
dFVSNpF7AxKbpVkUJHSchmymf3E8B84OB7x3rlECQKRlputjl50PKIGFitkCQQCo
Yx+1A1mEppMFN0s17r+AW16D9rXOJyYnI+0XWgpfQfZyUTEQhSenjlrkEmrsbXN7
BQD0b24HJHI4EgYl1AYxAkAGkFU452bO5xcnFEi354nApz8ygnWLlRzqM6SIljiB
l98OjyGUH3xSoo2jTFNP69Xm3El2ktLIhVHP5Jyb4KEe
-----END RSA PRIVATE KEY-----`)
		const encryptedMessage = data
		try {
			const decryptedMessage = decryptor.decrypt(encryptedMessage)
			console.log("decryptedMessage", decryptedMessage)
			return decryptedMessage
		} catch (error) {
			console.error('解密时发生错误:', error)
			uni.showToast({
				icon: "none",
				title: "解密失败"
			})
		}
	},
	decryptMessage(encryptedMsg) {
		const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDWZBewflJt+NTKY/bVWtn5aoJjF2a2hF7g3q+KevrXe7y3xJ/V
gMUUdp0/LVvl/YGMGS0Tro8PqUgh66CgqeNRBeREJd5H1Ns7VbFZKKVYnNWS4dWI
SaXeDCyD5Xma39tM2DJHYi68UngAzGNnRVXQuk5W4WY1am+WVtYhIFTU7wIDAQAB
AoGBALGUPrsGJyjIDxmFK5MVqa8aNd32KDHN+viv+x7tNpD+ARcGWo3yF0wX46/M
1m3uSTvOLrQ6xmzmfsT58xahIZMa/5zLtY2t7vXtjeVh1vFcUV3KqUvmcaD5QjN+
H6eZ015ecnAXfzAusgOMzbplR3FIjmUYSgHa4wGQnbjr9vnhAkEA6W4daoJNO8yQ
WY93CUhdyxNxwlAIu+XdOkNOhGMlfIhAcHcUBL18omaRb5imH4Y1n5UtN6hLg9rm
HQ1sSfHF9QJBAOseuAE9CSnCFOvakIATfYehOJbqGv4FFcOUEqZItBWI/3TDJjBh
WSBHOU31hbtHV0U0uz2oIoGxgpPEeUH8fNMCQH8imCbgXQxKt/vvZVfK8Dqgln7M
dFVSNpF7AxKbpVkUJHSchmymf3E8B84OB7x3rlECQKRlputjl50PKIGFitkCQQCo
Yx+1A1mEppMFN0s17r+AW16D9rXOJyYnI+0XWgpfQfZyUTEQhSenjlrkEmrsbXN7
BQD0b24HJHI4EgYl1AYxAkAGkFU452bO5xcnFEi354nApz8ygnWLlRzqM6SIljiB
l98OjyGUH3xSoo2jTFNP69Xm3El2ktLIhVHP5Jyb4KEe
-----END RSA PRIVATE KEY-----`
	    var decrypt = new JSEncrypt();
	    decrypt.setPrivateKey(privateKey);
	
	    var decodedMsg = atob(encryptedMsg);
	    var chunkSize = 128; // RSA解密每块数据的大小
	
	    var decryptedChunks = [];
	    for (var i = 0; i < decodedMsg.length; i += chunkSize) {
	        var chunk = decodedMsg.slice(i, i + chunkSize);
	        var decrypted = decrypt.decrypt(btoa(chunk));
	        if (decrypted === null) {
	            console.error("解密失败");
	            return null;
	        }
	        decryptedChunks.push(decrypted);
	    }
	
	    return decryptedChunks.join('');
	}
}